package mysql.cs.packet;

import common.Util.ByteUtil;
import mysql.MysqlPacket;
import mysql.cs.prop.Capabilities;

import java.io.IOException;

/**
 * int<1>	header	[ff] header of the ERR packet
 * int<2>	error_code	error-code
 * if capabilities & CLIENT_PROTOCOL_41 {
 *   string[1]	sql_state_marker	# marker of the SQL State
 *   string[5]	sql_state	SQL State
 * }
 * string<EOF>	error_message	human readable error message
 * @ClassName ErrorPacket
 * @Description TODO
 * @Author fengk
 * @Date 2018/8/28
 */

public class ErrorPacket extends MysqlPacket {
    public byte fieldCount;
    public int errorNumber;
    public byte sqlStateMarker;
    public byte[] sqlState;
    public String message;
    public void encode(byte[] data){
        int index=0;
        fieldCount=data[0];
        index++;
        errorNumber= ByteUtil.readUnsignedShortLittleEndian(data,index);
        index+=2;
        if((Capabilities.CLIENT_PROTOCOL_41&Capabilities.CAPABILITIES) != (long)0x00){
            sqlStateMarker=data[index];
            index++;
            sqlState=ByteUtil.readFixedLengthBytes(data,index,5);
            index+=5;
        }
        message=new String(ByteUtil.readFixedLengthBytes(data,index,data.length - index));
    }
    public byte[] decode() throws IOException {
        return null;
    }

    @Override
    public String toString() {
        return "ErrorPacket [errorNumber=" + errorNumber + ", fieldCount=" + fieldCount + ", message=" + message
                + ", sqlState=" + sqlStateToString() + ", sqlStateMarker=" + (char) sqlStateMarker + "]";
    }

    private String sqlStateToString() {
        StringBuilder builder = new StringBuilder(5);
        for (byte b : this.sqlState) {
            builder.append((char) b);
        }
        return builder.toString();
    }
}
